﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.Conventions.Service;
using StyleMVVM.Conventions.ViewModel;
using StyleMVVM.DependencyInjection;
using StyleMVVM.Logging;
using StyleMVVM.View;
using StyleMVVM.ViewModel;
#if NETFX_CORE
using Windows.UI.Xaml;

#else
using System.Windows;

#endif

namespace StyleMVVM.Conventions.View
{
	public sealed class ConventionsViewBinder : IViewBinder
	{
		private IConventionsService conventionsService;
		private IViewModelResolutionService viewModelResolutionService;

		public static void RegisterExport(IDependencyInjectionContainer container)
		{
			container.Register(typeof(ConventionsViewBinder))
			         .As(typeof(IViewBinder))
			         .ImportMethod("ImportServices")
			         .AndShared();
		}

		public void Bind(object view, object navigationParameter)
		{
			FrameworkElement frameworkElement = view as FrameworkElement;

			if (frameworkElement != null && !HasDataContext(frameworkElement))
			{
				IEnumerable<string> viewModelNames = conventionsService.ViewModelNameConventions(view.GetType());

				foreach (string viewModelName in viewModelNames)
				{
					if (viewModelResolutionService.ResolveViewModel(frameworkElement, viewModelName))
					{
						break;
					}
				}
			}
		}

		private bool HasDataContext(FrameworkElement frameworkElement)
		{
			object newValue = frameworkElement.ReadLocalValue(FrameworkElement.DataContextProperty);

			if (newValue == DependencyProperty.UnsetValue)
			{
				return false;
			}

			return true;
		}

		public void ImportServices(IConventionsService conventionsService,
		                           IViewModelResolutionService viewModelResolutionService)
		{
			this.conventionsService = conventionsService;
			this.viewModelResolutionService = viewModelResolutionService;
		}
	}
}